import { Component, OnInit } from '@angular/core';

import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, NavigationEnd } from '@angular/router';

import { Md5 } from 'ts-md5/dist/md5';

import { fadeIn, fadeOut, flyIn, flyOut } from "../common/animate.common";

import { User, ErrorMsg, Phone, PhoneErrorMsg } from '../models/user.model';

import { Check } from "../common/check";

import { LoginService } from "./login.service";

import { StorageService } from "../../app/common/storage.service";
import { HttpInterceptorService } from '../common/http-interceptor.service';

@Component({
    templateUrl: './forgetpw.component.html',
    styleUrls: ['./login.component.css'],
    animations: [fadeIn, fadeOut, flyIn, flyOut]
})

export class ForgetpwComponent {

    private check: Check = new Check();
    private localStorage = window.localStorage ? window.localStorage : null;
    public user: User = new User('default');

    navHeight:string = '80px';//nav高度
    forget:boolean = true;

    mobile:any;//手机号
    mobileIsAble:boolean=false;//是否验证过手机号
    code:any;//验证码
    errMsg:string;//错误提示
    picCodeShow:boolean;//是否显示图片验证码
    picCode:any;//是否显示图片验证码
    picShowTime:number = 3;//输入错误次数
    countdown:number = 60;//
    gottenPhoneCode:boolean;//验证码 是否可点

    uri = this.loginService.baseUrl;
    randomStr = new Date().getTime();
    imgSrc:string = this.uri + "/com-dyrs-mtsp-loginservice/images/imagecode?randomStr="+this.randomStr+"&r="+Math.random();


    pwd:any;//密码
    pwd1:any;
    checkDiff:boolean;
    

    constructor(private service: LoginService, private router: Router, private storage: StorageService,private loginService: HttpInterceptorService) { };

    ngOnInit() {
        this.user.code = this.localStorage ? this.localStorage.getItem('account') : '';
    }

    refresh(){
       this.randomStr = new Date().getTime();
        this.imgSrc = this.uri +"/com-dyrs-mtsp-loginservice/images/imagecode?randomStr="+this.randomStr+"&r="+Math.random();
    }

    //检查手机号
    checkMobile():boolean{
        if (!this.mobile) {
            this.errMsg = '手机号格式不正确';
            return false;
        }
        this.mobile = this.mobile.trim();
        if (this.mobile=='') {
            this.errMsg = '手机号格式不正确';
            return false;
        }
        if (!this.check.phone(this.mobile)) {
           
            this.errMsg = '手机号格式不正确';
            return false;
          } else {
            this.errMsg = '';     
          }
        //   this.userIsExistsByMobile();
         return true;

    }

    //验证手机号是否存在
    userIsExistsByMobile(call?):void {
        let params:any = {};
        params.mobile = this.mobile;
        this.service.employeeIsExistsByMobile(params).then(res => {
          if (res.result) {
            this.errMsg = '用户不存在';
            if (call) {
                call(false);
            }
          } else {   
            if (call) {
                this.gottenPhoneCode = true;
                this.count();
                call(true);
            }
          }
        });
        
      }
      //发送短信
      sendMsg(){
          //是否可点
        let b:boolean = this.checkMobile();
        if (b) {
            this.userIsExistsByMobile((s) => {
                if (s) {
                    let params:any = {};
                    params.number = this.mobile;
                    //发送
                   this.service.sendMsg(params).then(res => {
                       if (res.result) {
                        //    this.gottenPhoneCode = true;
                        //    this.count();
                       } else {
                        this.errMsg = res.msg;
                       }
    
                   });
                }

            })
        }

      }

      //倒计时
      count():void {
        this.countdown=60;
        let interval = setInterval(() => {
          this.countdown--;
          if (this.countdown==0) {
            this.gottenPhoneCode = false;
            clearInterval(interval);
          }
        },1000)
      }

      reset(){
           //是否可点
        let b:boolean = this.checkMobile();
        if (!b) {
            return;
        }
        if (!this.code) {
            this.errMsg = '验证码不正确';
            return ;
        }
        this.code = this.code.trim();
        if (this.code == '') {
            this.errMsg = '验证码不正确';
            return ;
        }

        this.userIsExistsByMobile(is => {
            if (is) {
                let params:any = {};
                params.number = this.mobile;
                params.code = this.code;
                if (this.picCodeShow) {
                    if (!this.picCode || this.picCode.trim()=='') {
                        this.errMsg = '请输入图片验证码';
                        return ;
                    }
                    params.key = this.randomStr;
                    params.picCode = this.picCode;
                }
                
                //发送
               this.service.validSms(params).then(res => {
                   if (res.result) {
                       this.forget = false;
                   } else {
                        // this.errMsg = '验证码不正确';
                        if (this.picCodeShow) {
                            this.refresh();
                        }
                        console.log(this.picCodeShow)
                        if (res.data > 3) {
                            this.picCodeShow = true;
                            console.log(this.picCodeShow)
                        }
                        this.errMsg = res.msg;
                   }

               });
                
            }
        });

      }

      /*************  修改密码 ************************ */
      checkPwd() {

        if (!this.pwd || this.pwd.trim()=='') {
            this.errMsg = '请输入新密码';
            return ;
        }
        this.pwd = this.pwd.trim();
        if (!this.check.password(this.pwd)) {
            this.errMsg = '请输入6-12位数字与字母组合';
            return ;
        }else {
            this.errMsg = '';
        }

        if (!this.pwd1 || this.pwd1.trim()=='') {
            this.errMsg = '请输入确认密码';
            return ;
        }

        this.pwd1 = this.pwd1.trim();
        // if (!this.check.password(this.pwd1)) {
        //     this.errMsg = '请输入6-12位数字与字母组合';
        //     return ;
        // }else {
        //     this.errMsg = '';
        // }
        this.diff();

      }

      diff () {
        if (this.pwd && this.pwd1 && this.pwd == this.pwd1) {
            this.errMsg = '';
        } else {
            this.errMsg = '您两次输入的密码不一致';
        }
      }

      resetPwd(){
          this.checkPwd();

          setTimeout(() => {
              if (this.errMsg =='') {
                let params:any = {};

                this.pwd = Md5.hashStr(this.pwd).toString();
                this.pwd1 = Md5.hashStr(this.pwd1).toString();
                params.accountPasswords = this.pwd;
                params.confirmPwds = this.pwd1;
                params.codes = this.mobile;
                params.smsCode = this.code;
                this.service.forgetPwd(params).then(res => {
                    if (res.result) {
                        this.router.navigateByUrl('login');
                    } else {
                        this.errMsg = res.msg;
                    }

                });

              }
              
          }, 100);

      }
}